import * as echarts from '../ec-canvas/echarts';
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    // tab切换  
    currentTab: 0,
    winWidth: 0,
    winHeight: 0,
    statistic:{},
    ecInt: {
      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
      // onInit: tChartx
    },
    interestData: {},
    ecFunnel:{
      lazyLoad: true
    },
    ecDealData:{},
    pickNameDeal: "近7天",
    ecActive: {
      lazyLoad: true
    },
    ecActiveData: {

    },
    ecInteraction: {
      lazyLoad: true
    },
    ecInteractionData: {
      list: []
    },
    pickerArr: [
      {
        name: "近7天",
        key: "7",
      },
      {
        name: "近15天",
        key: "15",
      },
      {
        name: "近30天",
        key: "30",
      }
    ],
    pickerName: "近7天",
  },
  /** 
       * 滑动切换tab 
       */
  bindChange: function (e) {

    var that = this;
    that.setData({ currentTab: e.detail.current });
    var day = new Date();
    var Today = util.formatDate(day)
    if (that.data.currentTab == 0 ) {
      that.getData();
    } else if (that.data.currentTab == 1 ) {
      day.setDate(day.getDate()-1)
      var yesterday = util.formatDate(day);
      that.getData(yesterday, yesterday);

    } else if (that.data.currentTab == 2 ) {
      day.setDate(day.getDate() - 6)
      var aboutseven = util.formatDate(day);;
      that.getData(aboutseven, Today);

    } else if (that.data.currentTab == 3 ) {
      day.setDate(day.getDate() - 29)
      var aboutMonth = util.formatDate(day);;
      that.getData(aboutMonth, Today);
    }

  },
  /** 
   * 点击tab切换 
   */
  swichNav: function (e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },  
  getData: function (startDate, endDate){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/data",
      data: {
        cusmallToken: cusmallToken,
        startDate: startDate || '',
        endDate: endDate || ''
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            statistic: data.model
          })
          
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  interest() {//兴趣统计
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interest",
      data: {
        cusmallToken: cusmallToken,
        mid: '',
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;

        if (data && 0 === data.ret) {
          ctx.setData({
            interestData: {
              toCompanyPerD: data.model.toCompanyPerD,
              toMePerD: data.model.toMePerD,
              toProductPerD: data.model.toProductPerD
            }
          })
          ctx.initInterest();
        } else {
          ctx.setData({
            interestData: {
              toCompanyPerD:33.33,
              toMePerD: 33.33,
              toProductPerD: 33.33
            }
          })
          ctx.initInterest();
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  initInterest(data) {
    let ctx = this;
    this.interestComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setInterestOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setInterestOption(chart) {
    let ctx = this;
    var option = {
      color: ["#FF5722", "#FF9800", "#00BCD4"],
      legend: {
        itemWidth:10,
        itemHeight:10,
        selectedMode: false,
        orient: 'horizontal',
        bottom: 40,
        data: ["对我感兴趣", "对产品感兴趣", "对公司感兴趣"]
      },
      series: [{
        label: {
          normal: {
            fontSize: 14,
            formatter: "{d}%",
            color: "#000000"
          }
        },
        type: 'pie',
        center: ['50%', '40%'],
        radius: [0, '60%'],
        data: [{
          value: ctx.data.interestData.toMePerD,
          name: '对我感兴趣'
        }, {
          value: ctx.data.interestData.toProductPerD,
          name: '对产品感兴趣'
        }, {
          value: ctx.data.interestData.toCompanyPerD,
          name: '对公司感兴趣'
        },
        ],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };
    chart.setOption(option);
  },
  //成交率
  deal:function (day){
    var ctx = this;

    var submitData = {
      cusmallToken: cusmallToken,
      countAll:false
    }
    if (day) {
      submitData.startDate = util.formatDate(new Date(Date.now() - (day * 86400000)));
      submitData.endDate = util.formatDate(new Date(Date.now() - (1 * 86400000)));
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/bargainFunnel",
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            dealData: data.model
          })
          // ctx.initDeal();
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });

    
  },
  initDeal:function (data){
    let ctx = this;
    this.dealComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setDealOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setDealOption(chart) {
    let ctx = this;
    var option = {
      backgroundColor: "#ffffff",
      color: ["#23bda5", "#f9bb40", "#ff7441", "#f76162"],
      // tooltip: {
      //   trigger: 'item',
      //   formatter: "{a} <br/>{b} : {c}%"
      // },
      legend: {
        selectedMode: false,
        itemWidth: 10,
        itemHeight: 10,
        bottom: "15%;",
        borderRadius: 100,
        data: ['≤50%', '≤80%', '≤99%', '≤100%']
      },
      calculable: true,
      series: [
        {
          top: 0,

          name: '',
          type: 'funnel',
          left: '10%',
          width: '80%',
          height: "80%",
          gap: 10,
          minSize: "30%",
          maxSize: "90%",
          label: {

            normal: {
              show: false,
              color: '#353535',
              position: 'left',

            },
            emphasis: {
              position: 'left',
              formatter: '{c}%'
            }
          },
          data: ctx.data.dealData
        },
        {
          name: '',
          type: 'funnel',
          top: 0,
          gap: 10,
          label: {
            normal: {
              position: 'inside',
              formatter: '{c}',
              textStyle: {
                color: '#fff'
              }
            }

          },
          itemStyle: {
            normal: {
              color: 'transparent',
              borderWidth: 0,
              opacity: 0
            }
          },
          data: ctx.data.dealData
        }


      ]
    };
    chart.setOption(option);
  },

  //活跃度
  active:function () {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/activeTrend",
      data: {
        cusmallToken: cusmallToken,
        mid: '',
        dayNum: 15
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var activeNum = [];
          var activeDay = [];
          for (let item of data.model.list) {
            activeNum.push(item.activeNum);
            activeDay.push(item.day.substring(5));
          }
          ctx.setData({
            ecActiveData: {
              activeNum: activeNum.reverse(),
              activeDay: activeDay.reverse()
            }
          })
          ctx.initActive();
        } else {

        }
      },
      fail() {

      },
      complete() {
        
      }
    });
  },
  initActive: function (data) {
    let ctx = this;
    this.activeComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setActiveOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setActiveOption(chart){
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      // tooltip: {
      //   show: true,
      //   trigger: 'axis'
      // },
      color: ["#37A2DA"],

      grid: {
        containLabel: true
      },

      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.ecActiveData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        name: "活跃度",
        type: 'line',
        smooth: true,
        data: ctx.data.ecActiveData.activeNum
      }]
    };
    chart.setOption(option);
  },
 //互动统计
  interaction() {//客户互动数据
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interaction",
      data: {
        cusmallToken: cusmallToken,
        mid: ""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            ecInteractionData: {
              list: [data.model.thumbs, 
              data.model.comment, data.model.askGoods, 
              data.model.forward, data.model.call, 
              data.model.save, data.model.addMemory]
            }
          })
          ctx.initInteraction();
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });

  },
  initInteraction(data) {
    let ctx = this;
    this.interactionComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setInteractionOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setInteractionOption(chart) {
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      grid: {
        containLabel: true
      },

      xAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis:
        {
          type: 'category',
          axisTick: { show: false },
          data: ['点赞', '评论', '咨询产品', '转发', '拨打电话', '保存电话', '印象标签'],
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666'
          }
        }
      ,
      series: [{
        smooth: true,
        type: 'bar',
        label: {
          normal: {
            show: true,
            position: 'inside'
          }
        },
        data: ctx.data.ecInteractionData.list,
        itemStyle: {
          normal: {
            color: function (params) {
              var colorList = ["#FF5722", "#00BCD4", "#9E9E9E", "#616161", "#795548", "#009688", "#FF9800"];
              return colorList[params.dataIndex];
            }
          }
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }]
    };

    chart.setOption(option);
  },
  bindPickerChange(e) {
    let ctx = this;
    let day = this.data.pickerArr[e.detail.value].key;
    let name = this.data.pickerArr[e.detail.value].name;
    let target = e.currentTarget.dataset.target;
    if ("dealper" == target) {
      ctx.deal(day);
        ctx.setData({
          pickNameDeal: name
        });
      }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    }); 
    this.dealComponent = this.selectComponent('#mychart-dom-funnel');
    this.interestComponent = this.selectComponent('#mychart-dom-pie');
    this.activeComponent = this.selectComponent('#mychart-dom-line');
    this.interactionComponent = this.selectComponent('#mychart-dom-bar');
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
    });
    that.interest();
    that.deal(7);
    that.active();
    that.interaction();
    that.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))